/**
 * Created by callmesoul on 2017/4/10.
 */
// var jwt = require('jsonwebtoken');
var Oauth = require('co-wechat-oauth');
module.exports = (options,app) => {
    return async function (ctx,next) {

        var oauthApi = new Oauth(ctx.session.wechat.appId,ctx.session.wechat.appSecret,async function (openid) {
            var user= await ctx.model.User.findOne({where:{openid:openid}});
            return user.token;
        },async function (openid,token) {
            var user= await ctx.model.User.findOne({where:{openid:openid}});
            if(user){
               await ctx.model.User.update({
                   token:token
               },{
                   where:{openid:openid}
               })
            }
        });
        var url=ctx.request.url;
        console.log(ctx.request)
        if(!ctx.session.user && ctx.request.path!='/oauth/redirect' && !ctx.request.query.noappid){
            var toUurl= oauthApi.getAuthorizeURL('http://nochat.callmesoul.cn/oauth/redirect',url,'snsapi_userinfo');
            ctx.redirect(toUurl);
            // await next();
        }else {
            if(ctx.session.user){
                console.log("ctx.session.user.wechatId",ctx.session.user.wechatId)
                console.log("ctx.session.wechat.id)",ctx.session.wechat.id)
                if(ctx.session.user.wechatId==ctx.session.wechat.id){
                    console.log('--------用户信息 wechat_oauth.js----------');
                    console.log(ctx.session.user.id);
                    console.log(ctx.session.user.nickname);
                    console.log(ctx.session.user.openid);
                    console.log('-------------------------');
                    await next();
                }else{
                    var toUurl= oauthApi.getAuthorizeURL('http://nochat.callmesoul.cn/oauth/redirect',url,'snsapi_userinfo');
                    ctx.redirect(toUurl);
                }
            }else{
                await next();
            }

        }

    };
};
